<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/2/1 0001
 * Time: 10:53
 */

namespace App\Base\Middleware;

use App\Base\Models\ResponseModel;
use Illuminate\Http\Request;
use Closure;

class Response
{
    private $responseModel;

    public function __construct(ResponseModel $responseModel)
    {
        $this->responseModel = $responseModel;
    }
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($response->exception == null) {
            $content = $response->getOriginalContent();

            $classname="";
            if(is_object($content)){
                $classname=get_class($content);
            }
            $this->responseModel->setStatus(ResponseModel::DEFAULT_STATUS_SUCCESS);
            $this->responseModel->setData($content);
            if(!empty($classname)){

                if(interface_exists($classname)||class_exists($classname)){

                    if($classname=="Illuminate\Pagination\LengthAwarePaginator"){
                        $count=$content->total();
                        $this->responseModel->setCount($count);
                        $this->responseModel->setData($content->items());

                    }
                }
            }

            $this->responseModel->setMsg('操作成功.');
            $response->setContent($this->responseModel);
        }
        return $response;
    }
}